#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/10/2 16:15
# @Author  : AshJo
# @Desc    : FTP服务端
# @Filename: server.py.py
# @Version : v1.0
"""

import os
import sys
import json
import struct
import socket
import hashlib


# 下载
def download():
    abs_path = r'D:\Zend\livecut.mp4'
    filename = os.path.basename(abs_path)
    filesize = os.path.getsize(abs_path)
    dic = {'filename': filename, 'filesize': filesize}
    my_send(conn, dic)
    with open(abs_path, mode='rb') as f:
        while filesize > 0:
            content = f.read(1024)
            filesize -= len(content)
            conn.send(content)


# 上传
def upload():
    msg = my_recv(conn)
    with open(msg['filename'], mode='wb') as f:
        while msg['filesize'] > 0:
            content = conn.recv(1024)
            msg['filesize'] -= len(content)
            f.write(content)


# 发送
def my_send(conn, dic):
    str_dic = json.dumps(dic)
    b_dic = str_dic.encode('utf-8')
    mlen = struct.pack('i', len(b_dic))
    conn.send(mlen)
    conn.send(b_dic)


# 接收
def my_recv(conn):
    msg_len = conn.recv(4)
    dic_len = struct.unpack('i', msg_len)[0]
    msg = conn.recv(dic_len).decode('utf-8')
    msg = json.loads(msg)
    return msg


def get_md5(username, password):
    md5 = hashlib.md5(username.encode('utf-8'))
    md5.update(password.encode('utf-8'))
    return md5.hexdigest()


def login(conn):
    flag = True
    while flag:
        msg = my_recv(conn)
        with open('userinfo') as f:
            for line in f:
                username, password = line.strip().split('|')
                if username == msg['username'] and password == get_md5(username, msg['password']):
                    res, flag = True, False
                    break
            else:
                res = False
            dic = {'operate': 'login', 'result': res}
            my_send(conn, dic)


sk = socket.socket()
sk.bind(('127.0.0.1', 9000))
sk.listen()

conn, addr = sk.accept()

# 登录
login(conn)

# 接收消息，根据用户的选择上传和下载
opt_dic = my_recv(conn)
if hasattr(sys.modules[__name__], opt_dic['operate']):
    getattr(sys.modules[__name__], opt_dic['operate'])()

conn.close()
sk.close()
